/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.oss.model.BladeFile;
import org.springblade.core.tool.utils.FileUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.admin.dto.SupplierFullDTO;
import org.springblade.modules.admin.dto.SupplierPageDTO;
import org.springblade.modules.admin.entity.Supplier;
import org.springblade.modules.admin.entity.SupplierContacts;
import org.springblade.modules.admin.service.ISupplierContactsService;
import org.springblade.modules.admin.vo.SupplierContactsVO;
import org.springblade.modules.admin.vo.SupplierPageVO;
import org.springblade.modules.admin.vo.SupplierVO;
import org.springblade.modules.admin.mapper.SupplierMapper;
import org.springblade.modules.admin.service.ISupplierService;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.modules.resource.entity.Attach;
import org.springblade.modules.resource.service.IAttachService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 供应商表 服务实现类
 *
 * @author ysq
 * @since 2023-08-09
 */
@Service
public class SupplierServiceImpl extends BaseServiceImpl<SupplierMapper, Supplier> implements ISupplierService {

	@Autowired
	private ISupplierContactsService supplierContactsService;

	@Autowired
	private IAttachService attachService;


	@Override
	@Transactional(rollbackFor = Exception.class)
	public Boolean addFull(SupplierFullDTO supplierFull) {
		// 当没有传 id 时， 新增
		Long id = supplierFull.getSupplier().getId();
		if (Func.isNull(id) || id == 0 || Func.isBlank(id.toString())){
			// 新增供应商
			Supplier supplier = supplierFull.getSupplier();
			this.save(supplier);
			// 2024-07-08 修改为前端直传OSS后, 手动存储Attach
			List<Attach> fileList = supplierFull.getFileList();
			if(!Func.isEmpty(fileList)){
				fileList.forEach(f -> {
					String originalName = f.getOriginalName();
					String fileExtension = FileUtil.getFileExtension(originalName);
					f.setExtension(fileExtension);
				});
				attachService.saveBatch(fileList);
			}
			// 新增供应商联系人
			List<SupplierContacts> supplierContactsList = supplierFull.getContactsList();
			if(Func.isEmpty(supplierContactsList)){
				return true;
			}
			for (SupplierContacts supplierContacts : supplierContactsList) {
				supplierContacts.setSupplierId(supplier.getId());
			}
			return supplierContactsService.saveBatch(supplierContactsList);
		} else {
			// 修改供应商
			Supplier supplier = supplierFull.getSupplier();
			this.updateById(supplier);
			// 2024-07-08 修改为前端直传OSS后, 手动存储Attach
			List<Attach> fileList = supplierFull.getFileList();
			if(!Func.isEmpty(fileList)){
				fileList.forEach(f -> {
					String originalName = f.getOriginalName();
					String fileExtension = FileUtil.getFileExtension(originalName);
					f.setExtension(fileExtension);
				});
				attachService.saveBatch(fileList);
			}
			// 修改供应商联系人
			// 先删除当前供应商全部联系人
			supplierContactsService.lambdaUpdate()
				.eq(SupplierContacts::getSupplierId, supplier.getId())
				.remove();
			// 再新增
			List<SupplierContacts> supplierContactsList = supplierFull.getContactsList();
			if(Func.isEmpty(supplierContactsList)){
				return true;
			}
			for (SupplierContacts supplierContacts : supplierContactsList) {
				supplierContacts.setId(null);
				supplierContacts.setSupplierId(supplier.getId());
			}
			// 批量新增
			return supplierContactsService.saveBatch(supplierContactsList);
		}
	}

	@Override
	public Boolean deleteContacts(List<Long> toLongList) {
		// 根据传入的供应商id 获取联系人列表
		for (Long aLong : toLongList) {
			List<SupplierContacts> list = supplierContactsService.list(new LambdaQueryWrapper<SupplierContacts>()
				.eq(SupplierContacts::getSupplierId, aLong)
			);
			List<Long> idList = new ArrayList<>();
			for (SupplierContacts supplierContacts : list) {
				Long id = supplierContacts.getId();
				idList.add(id);
			}
			supplierContactsService.removeByIds(idList);
		}
		// 删除联系人
		return true;
	}

	@Override
	public List<SupplierContactsVO> contactsList(Long supplierId) {
		List<SupplierContacts> list = supplierContactsService.list(new
			LambdaQueryWrapper<SupplierContacts>()
			.eq(SupplierContacts::getSupplierId, supplierId)
		);
		List<SupplierContactsVO> supplierContactVOS = new ArrayList<>();
		for (SupplierContacts supplierContacts : list) {
			SupplierContactsVO supplierContactsVO = new SupplierContactsVO();
			BeanUtils.copyProperties(supplierContacts, supplierContactsVO);
			supplierContactVOS.add(supplierContactsVO);
		}
		return supplierContactVOS;
	}

	@Override
	public IPage<SupplierPageVO> pageByCondition(IPage<SupplierPageVO> page, SupplierPageDTO supplierPageDTO) {
		IPage<SupplierPageVO> supplierPageVOIPage = baseMapper.pageByCondition(page, supplierPageDTO);
		// 时间紧，供应商数据量不大的情况先手动分页,后期优化
		// 获取结果
		List<SupplierPageVO> r = baseMapper.handlePage(supplierPageDTO);
		supplierPageVOIPage.setTotal(r.size());
		if(Func.isNull(r) || Func.isEmpty(r)){
			return supplierPageVOIPage;
		}
		List<SupplierPageVO> records = pageList(r, supplierPageDTO.getCurrent(), supplierPageDTO.getSize());
		// 遍历结果
		for (SupplierPageVO record : records) {
			// 获取每个结果contractFiles
			String contractFiles = record.getContractFiles();
			if (Func.isBlank(contractFiles) || Func.isNull(contractFiles) ){
				continue;
			}
			// 根据逗号拆分 contractFiles 字符串 为数组
			String[] split = contractFiles.split(",");
			List<Attach> fileList = new ArrayList<>();
			// 将数组转换为集合
			// 遍历集合
			for (String link : split) {
				Attach a = new Attach();
				a.setLink(link);
				// 根据url 获取文件信息
				List<Attach> attachList = attachService
					.list(Condition.getQueryWrapper(a));
				// 多个情况取一个就好
				if(!Func.isEmpty(attachList)){
					fileList.add(attachList.get(0));
				}
			}
			record.setFileList(fileList);
		}
		supplierPageVOIPage.setRecords(records);
		return supplierPageVOIPage;
	}

	/**
	 * @param list     分页前的集合
	 * @param pageNum  页码
	 * @param pageSize 页数
	 * @param <T> 统配符
	 * @return 分页后的集合
	 */
	public <T> List<T> pageList(List<T> list, int pageNum, int pageSize) {
		//计算总页数
		int page = list.size() % pageSize == 0 ? list.size() / pageSize : list.size() / pageSize + 1;
		//兼容性分页参数错误
		pageNum = pageNum <= 0 ? 1 : pageNum;
		pageNum = pageNum >= page ? page : pageNum;
		// 开始索引
		int begin = 0;
		// 结束索引
		int end = 0;
		if (pageNum != page) {
			begin = (pageNum - 1) * pageSize;
			end = begin + pageSize;
		} else {
			begin = (pageNum - 1) * pageSize;
			end = list.size();
		}
		return list.subList(begin, end);
	}

}
